package LinkedList;//给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
//
// 
//
// 示例 1： 
//
// 
//输入：head = [1,2,3,4,5], k = 2
//输出：[4,5,1,2,3]
// 
//
// 示例 2： 
//
// 
//输入：head = [0,1,2], k = 4
//输出：[2,0,1]
// 
//
// 
//
// 提示： 
//
// 
// 链表中节点的数目在范围 [0, 500] 内 
// -100 <= Node.val <= 100 
// 0 <= k <= 2 * 10⁹ 
// 
// Related Topics 链表 双指针 👍 648 👎 0


//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class rotateRight1 {
    public ListNode rotateRight1(ListNode head, int k) {
        //将链表连成一个圈，然后取新头就行。
        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        //对链表计数
        int n = 1;
        ListNode iter = head;
        while (iter.next != null) {
            iter = iter.next;
            n++;
        }
        //计算真实次数
        int add = n - k % n;
        if (add == n) {
            return head;
        }
        //将尾节点指向头
        iter.next = head;
        //找到新头节点
        while (add-- > 0) {
            iter = iter.next;
        }
        //下一个即为新头
        ListNode ret = iter.next;
        iter.next = null;  //截断
        return ret;
    }

    public ListNode rotateRight(ListNode head, int k) {
        //可以找到倒数第k个节点，即新头，连接到原首节点
        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        //对链表计数
        int n = 1;
        ListNode iter = head;
        while (iter.next != null) {
            iter = iter.next;
            n++;
        }
        k = k % n; //真实移动次数
        if(k==0){
            return head;
        }
        ListNode fast = head;
        while(k-->0){
            fast = fast.next;
        }
        ListNode slow = head;
        while(fast.next!=null){
            fast = fast.next;
            slow = slow.next;
        }
        //当前slow 在新头前一节点.
        ListNode nhead = slow.next;
        iter = nhead;
        slow.next = null;
        while(iter.next!=null){
            iter = iter.next;
        }
        iter.next = head;
        return nhead;

    }
}
//leetcode submit region end(Prohibit modification and deletion)
